# myapp/views.py
import hashlib
import re

from django.conf import settings
from django.shortcuts import render,HttpResponse,redirect

from .forms import ProfileEditForm

from .models import UserProfile
from .models import User, Order, OrderItem, Product  # 导入所有需要的模型
from django.http import HttpResponse, HttpResponseNotAllowed
from django.shortcuts import render, get_object_or_404
from .models import Product_order
from django.db.models import Q
from django.core.paginator import Paginator, EmptyPage
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
import json
from django.core.cache import cache
from .chat import SecondhandSparkBot
from django.contrib.auth import logout
from django.shortcuts import redirect

def logout_view(request):
    logout(request)
    # 直接重定向到主页（例如首页）
    return redirect('index')
def index(request):
    try:
        username = request.session['username']
    except KeyError:
        username = None
    return render(request, "user/index.html", context={
        "username": username
    })


def login(request):
    method = request.method
    if method == "GET":
        return render(request, "user/login.html")
    elif method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")

        try:
            user = User.objects.get(username=username)
            res = password + settings.SECRET_KEY
            encrypted_pwd = hashlib.md5(res.encode("utf-8")).hexdigest()

            if encrypted_pwd == user.password:
                request.session['username'] = user.username
                html = """
                <script>
                    alert('登录成功！');
                    window.location.href = '/user/index';
                </script>
                """
            else:
                html = """
                <script>
                    alert('密码错误，请重新输入！');
                    window.location.href = '/user/login';
                </script>
                """
            return HttpResponse(html)

        except User.DoesNotExist:
            html = """
            <script>
                alert('用户名不存在！');
                window.location.href = '/user/login';
            </script>
            """
            return HttpResponse(html)




def register(request):
    method = request.method
    if method == "GET":
        return render(request, "user/register.html")
    elif method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        confirm_password = request.POST.get("confirm-password")
        email = request.POST.get("email")

        # 检查用户名是否已存在
        if User.objects.filter(username=username).exists():
            return render(request, "user/register.html", {
                "error": "用户名已被注册，请尝试新的用户名！"
            })

        # 检查密码复杂度
        if not re.match(r'^(?=.*\d)(?=.*[a-zA-Z])(?=.*[\W_]).{6,16}$', password):
            return render(request, "user/register.html", {
                "error": "密码必须为6-16位字符，包含数字、字母和特殊符号！"
            })

        # 检查两次输入的密码是否一致
        if password != confirm_password:
            return render(request, "user/register.html", {
                "error": "两次输入的密码不一致！"
            })

        # 对密码进行加密
        res = password + settings.SECRET_KEY
        encrypted_pwd = hashlib.md5(res.encode("utf-8")).hexdigest()

        # 创建用户
        user = User.objects.create(username=username, password=encrypted_pwd, email=email)
        UserProfile.objects.create(user=user)

        return redirect('login')


def order_list(request):
    """显示所有订单及其商品信息"""
    if request.method == "GET":
        try:
            username = request.session['username']  # 从 session 中获取用户名
            user = User.objects.get(username=username)  # 通过用户名获取用户对象
            user_id = user.id  # 获取用户 ID
            orders = Order.objects.filter(user_id=user_id).order_by('-created_at')  # 过滤订单

            # 获取每个订单的商品信息
            order_details = []
            for order in orders:
                order_items = OrderItem.objects.filter(order=order)  # 获取订单项
                items_with_products = []
                for item in order_items:
                    product = Product.objects.get(id=item.product_id)  # 获取商品信息
                    items_with_products.append({
                        'product_name': product.name,
                        'product_price': product.price,
                        'product_image': product.image.url,
                        'quantity': item.quantity,
                        'unit_price': item.unit_price
                    })
                order_details.append({
                    'order': order,
                    'items': items_with_products
                })

        except (KeyError, User.DoesNotExist):
            # 如果 session 中没有用户名或用户不存在，返回空订单列表
            order_details = []

        return render(request, 'user/order_list.html', {'order_details': order_details})
    else:
        # 不支持的请求方法
        return HttpResponseNotAllowed(['GET'])


def center(request):
    try:
        username = request.session['username']  # 从 session 中获取用户名
        user = User.objects.get(username=username)  # 获取用户对象
        profile, created = UserProfile.objects.get_or_create(user=user)  # 获取或创建 UserProfile
        return render(request, 'user/center.html', {
            'profile': profile,
            'user': user  # 传递用户对象到模板
        })
    except KeyError:  # session 中没有 username
        return redirect('index')  # 未登录跳转到首页
    except User.DoesNotExist:  # 用户不存在
        return redirect('index')  # 跳转到首页


# myapp/views.py
def profile_edit(request):
    try:
        username = request.session['username']  # 从 session 中获取用户名
        user = User.objects.get(username=username)  # 获取用户对象
        profile = user.userprofile  # 获取 UserProfile

        if request.method == 'POST':
            form = ProfileEditForm(request.POST, instance=profile)
            if form.is_valid():
                form.save()
                return redirect('center')
        else:
            form = ProfileEditForm(instance=profile)

        return render(request, 'user/profile_edit.html', {'form': form})
    except KeyError:  # session 中没有 username
        return redirect('index')  # 未登录跳转到首页
    except User.DoesNotExist:  # 用户不存在
        return redirect('index')  # 跳转到首页




def product_list(request):
    # 初始化基础查询集
    base_queryset = Product_order.objects.filter(is_sold=False)

    # 搜索关键词处理
    search_query = request.GET.get('q')
    if search_query:
        base_queryset = base_queryset.filter(
            Q(name__icontains=search_query) |
            Q(description__icontains=search_query) |
            Q(tags__name__icontains=search_query)
        ).distinct()

    # 分类筛选
    selected_category = request.GET.get('category')
    if selected_category and selected_category != '':
        base_queryset = base_queryset.filter(category=selected_category)

    # 价格范围处理
    min_price = request.GET.get('min_price')
    max_price = request.GET.get('max_price')
    try:
        min_price = float(min_price) if min_price else None
        max_price = float(max_price) if max_price else None
        if min_price and max_price and min_price > max_price:
            min_price, max_price = max_price, min_price
    except (TypeError, ValueError):
        min_price = max_price = None

    if min_price is not None:
        base_queryset = base_queryset.filter(price__gte=min_price)
    if max_price is not None:
        base_queryset = base_queryset.filter(price__lte=max_price)

    # 商品状态筛选
    selected_conditions = request.GET.getlist('conditions')
    if selected_conditions:
        base_queryset = base_queryset.filter(condition__in=selected_conditions)

    # 排序处理
    sort_mapping = {
        '-created_at': '最新发布',
        'price': '价格升序',
        '-price': '价格降序',
        '-views': '人气优先'
    }
    sort_key = request.GET.get('sort', '-created_at')
    valid_sort = sort_key if sort_key in sort_mapping else '-created_at'
    ordered_queryset = base_queryset.order_by(valid_sort)

    # 分页处理
    paginator = Paginator(ordered_queryset, 16)
    page_number = request.GET.get('page', 1)
    try:
        paginated_products = paginator.page(page_number)
    except EmptyPage:
        paginated_products = paginator.page(paginator.num_pages)

    # 准备模板上下文
    context = {
        'products': paginated_products,
        'categories': Product_order.CATEGORY_CHOICES,
        'conditions': Product_order.CONDITION_CHOICES,
        'selected_conditions': selected_conditions,
        'current_sort': valid_sort,
        'sort_options': sort_mapping,
        'request_params': {
            'q': search_query,
            'category': selected_category,
            'min_price': min_price,
            'max_price': max_price
        }
    }

    return render(request, 'user/product_list.html', context)


# 保持 product_detail 和 create_order 视图不变
def product_detail(request, pk):
    product = get_object_or_404(Product_order, pk=pk)
    product.views += 1
    product.save()
    return render(request, 'user/product_detail.html', {'product': product})


def create_order(request, product_id):
    product = get_object_or_404(Product_order, id=product_id)
    return render(request, 'user/order_create.html', {'product': product})

@csrf_exempt
def chat_api(request):
    """
    处理 AI 对话请求
    """
    if request.method == "GET":
        # 处理 GET 请求（例如返回页面）
        return render(request, "user/ai.html")
    elif request.method == "POST":
        try:
            # 解析 JSON 请求体
            data = json.loads(request.body)
            user_message = data.get('message', '')

            # 输入验证
            if not user_message or len(user_message) > 500:
                return JsonResponse({'error': 'Invalid input'}, status=400)

            # 获取或创建会话历史
            session_key = request.session.session_key
            if not session_key:
                request.session.create()
                session_key = request.session.session_key

            cache_key = f"chat_history_{session_key}"
            history = cache.get(cache_key, [])

            # 调用大模型
            bot = SecondhandSparkBot()
            ai_response = bot.ask(user_message)  # 直接调用 ask 方法

            # 更新历史记录（保留最近10条）
            updated_history = (history + [{'user': user_message, 'ai': ai_response}])[-10:]
            cache.set(cache_key, updated_history, timeout=3600)

            return JsonResponse({
                'reply': ai_response,
                'history': updated_history
            }, status=200)

        except Exception as e:
            print(f"[ERROR] API Exception: {str(e)}")
            return JsonResponse({'error': 'Service unavailable'}, status=500)

        return JsonResponse({'error': 'Method not allowed'}, status=405)


